from django.urls import path
from channels.auth import AuthMiddlewareStack # 认证中间件栈
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator

from zanhu02.messager.consumers import MessagesConsumer
from zanhu02.notifications.consumers import NotificationsConsumer

# self.scope['type'] 获取协议类型
# self.scope['url_route']['kwargs']['username'] 获取url中的关键字
# channels routing是scope级别的,一个连接只能由一个consumer接收和处理

application = ProtocolTypeRouter({
    # 普通的HTTP协议请求不需要我们手动添加,框架会自动加载
    'websocket' : AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter([
        path('ws/notifications/', NotificationsConsumer),
        path('ws/<str:username>/', MessagesConsumer),
        ])),
    )
})
"""
AuthMiddlewareStack用于WebSocket认证,集成了CookieMiddleWare,SessionMiddleWare,
AuthMiddleware,兼容Django认证系统

AllowedHostsOriginValidator Django项目的ALLOWED_HOSTS,防止通过websocket进行CSRF攻击
        允许访问的源站与settings.py文件中的ALLOWED_HOSTS相同
"""
